﻿//友情链接 轮播图 Vue插件
var vuelinktable = Vue.extend({
    //https://cn.vuejs.org/v2/guide/components-props.html#Prop-%E7%9A%84%E5%A4%A7%E5%B0%8F%E5%86%99-camelCase-vs-kebab-case
    //props: 注意命名规则 父组件调用<link-table :item-data="itemData" />
    props: {
        itemData: Object
    },
    data() {
        var validateUrl = (rule, value, callback) => {
            if ((value === '' || value === '#') && this.editForm.target !== "_no") {
                callback(new Error('请输入链接URL'));
            } else if ((value === '' || value === '#') && this.editForm.target === "_no") {
                callback();
            } else {
                var validUrl = /^(https:\/\/|http:\/\/|www\.)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/]+)+$/.test(value.split('?')[0]);
                if (!validUrl) {
                    callback(new Error('URL地址不符合校验规则'));
                } else callback();
            }
        };
        return {
            isImageLink: this.itemData.options.isImageLink,
            editFormVisible: false,
            editTableIndex: -1,
            tableData: this.itemData.options.initData ? this.itemData.items : [],
            editLoading: false,
            editForm: {},
            uploadImageChoose: false,
            newRow: null,
            isCloudUpload: false,
            isEnlargeImage: false,      //放大图片
            enlargeImage: '',           //放大图片地址
            isSortDialogVisible: false, //设置排序编辑框
            sortNum: 0,                 //绑定行排序号
            targetOptions: [{
                value: '_blank',
                label: '新窗口'
            }, {
                value: '_self',
                label: '页内跳转'
            }, {
                value: '_no',
                label: '无链接'
            }],
            formRules: {
                title: [
                    { required: true, message: '请输入标题(显示名称)', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                desc: [
                    { min: 0, max: 50, message: '长度在 50 个字符以内', trigger: 'blur' }
                ],
                contents: [
                    { min: 0, max: 100, message: '长度在 100 个字符以内', trigger: 'blur' }
                ],
                url: [
                    { validator: validateUrl, trigger: 'blur' }
                ],
                target: [
                    { required: true, message: '请选择链接跳转方式', trigger: 'change' }
                ]
            }
        };
    },
    watch: {
        itemData: {
            immediate: false,
            deep: true,
            handler(val) {
                this.isImageLink = val.options.isImageLink;
                //let tablenLen = this.tableData.length;
                //this.tableData.splice(0, tablenLen);
                //this.newRow = null;
            }
        }
    },
    methods: {
        addRow() {
            let _this = this;
            if (this.newRow !== null) {
                this.$message({
                    message: '请先编辑或移除上一条新添加的行数据',
                    type: 'warning'
                });
                return;
            }
            if (this.itemData.options.limitNum > 0) {
                if (this.tableData.length >= this.itemData.options.limitNum) {
                    _this.$message.error("允许添加数量超过数量限制");
                    return;
                }
            }
            this.newRow = {
                id: 0,             //如果是图片链接则保存上传图片Id，文字链接为0
                imgUrl: '/images/default-image.png',        //如果是图片链接存储图片Url
                title: '默认标题',  //链接(或图片)显示名称
                desc: '',          //链接(或图片)描述信息
                contents: '',
                url: '#',          //跳转链接地址
                target: '_no',     //地址链接跳转方式 _blank新窗口 _self页内跳转 _no不跳转
                sort: _this.tableData.length + 1
            };
            this.tableData.push(this.newRow);
        },
        targetFormatter(row, column) {
            var display = "";
            this.targetOptions.forEach(option => {
                if (row.target === option.value)
                    display = option.label;
            });
            return display;
        },
        handleDelete(index, row) {
            if (row.id === 0) {//未编辑的新增行
                this.newRow = null;
            }
            this.tableData.splice(index, 1);
            this.$message({
                message: '操作成功，请注意提交保存，否则操作将无效',
                type: 'warning'
            });
        },
        //handleIsImageLinkChange(checked) {
        //    this.tableData.forEach(item => {
        //        this.$set(item, 'isImageLink', checked);
        //    });
        //},
        handleEdit: function (index, row) {
            this.editFormVisible = true;
            this.editForm = Object.assign({}, row);
            this.editTableIndex = index;
            this.uploadImageChoose = false;
        },
        editSubmit: function () {
            let _this = this;
            this.$refs.editForm.validate((valid) => {
                if (!valid) {
                    console.error('error submit!!');
                    return false;
                }
                if (_this.isImageLink) {
                    if (_this.uploadImageChoose) { //选择了图片提交则连同编辑信息一起上传
                        _this.$refs.imageupload.submit();
                    } else { //如果只编辑信息提交的话则不上传图片
                        if (_this.editForm.id > 0) {
                            _this.$confirm('是否只修改编辑信息?', '提示', {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning'
                            }).then(() => {
                                var postData = {
                                    Id: _this.editForm.id,
                                    TitleAttribute: _this.editForm.title,
                                    AltAttribute: _this.editForm.desc,
                                    LinkUrl: _this.editForm.url
                                };
                                _this.editLoading = true;
                                httpapi.fetchPost('/api/backend/business/resourcemanage/edit', postData).then(res => {
                                    _this.editLoading = false;
                                    if (!httpapi.checkResponse(res))
                                        //输入信息校验错误
                                        _this.$message.error(res.message);
                                    else {//Success
                                        _this.$message({
                                            message: '操作成功，请注意提交保存，否则操作将无效',
                                            type: 'warning'
                                        });
                                        _this.editForm.imgUrl = res.data.FileUrl;
                                        _this.editForm.id = res.data.FileUploadId;
                                        _this.$set(_this.tableData, _this.editTableIndex, _this.editForm);
                                        _this.editForm = {};
                                        _this.editFormVisible = false;
                                        if (_this.tableData.length === _this.editTableIndex)
                                            _this.newRow = null;
                                        _this.editTableIndex = -1;
                                    }
                                }).catch(error => console.error(error));
                            }).catch(() => {
                                this.$message({
                                    type: 'info',
                                    message: '请选择图片上传'
                                });
                            });
                        } else {
                            _this.$message.error("未选择上传图片");
                        }

                    }
                } else { //友情链接-文字
                    _this.editForm.imgUrl = "";
                    _this.editForm.id = 0;
                    _this.$set(_this.tableData, _this.editTableIndex, _this.editForm);
                    _this.editForm = {};
                    _this.editFormVisible = false;
                    _this.editTableIndex = -1;
                    _this.newRow = null;
                    _this.$message({
                        message: '操作成功，请注意提交保存，否则操作将无效',
                        type: 'warning'
                    });
                }
            });
        },
        uploadImage: function (params) {
            let _this = this;
            _this.editLoading = true;
            var formData = new FormData();
            formData.append("Form.Files", params.file);
            var uploaddata = {
                Id: _this.editForm.id,
                Category: "AdvImage",
                TitleAttribute: _this.editForm.title,
                AltAttribute: _this.editForm.desc,
                StoreType: _this.isCloudUpload ? "QiniuCloud" : "LocalStorage",
                LinkUrl: _this.editForm.url
            };
            //追加额外的参数
            Object.getOwnPropertyNames(uploaddata).forEach(function (key) {
                uploaddata[key] = typeof uploaddata[key] === 'function' ? uploaddata[key]() : uploaddata[key];
                formData.append(key, uploaddata[key]);
            });
            var xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', '/api/backend/business/resourceupload');
            xhr.onload = function () {
                _this.editLoading = false;
                var json;
                if (xhr.status !== 200) {
                    console.error('HTTP Error: ' + xhr.status);
                    _this.$message.error("上传失败： Http Error:" + xhr.status);
                    return;
                }
                json = JSON.parse(xhr.responseText);
                if (!json || json.state !== 200) {
                    _this.$message.error(json.message);
                    return;
                }
                if (_this.editForm.id === 0) { //newRow set null
                    _this.newRow = null;
                }
                _this.editForm.imgUrl = json.data.FileUrl;
                _this.editForm.id = json.data.FileUploadId;
                _this.$set(_this.tableData, _this.editTableIndex, _this.editForm);
                _this.editForm = {};
                _this.editFormVisible = false;
                _this.editTableIndex = -1;
                _this.$refs.imageupload.clearFiles();  //清空上传列表，避免多次上传
                _this.$message({
                    message: '操作成功，请注意提交保存，否则操作将无效',
                    type: 'warning'
                });
            };
            xhr.send(formData);
        },
        editPreview: function (file, fileList) {
            var _this = this;
            var event = event || window.event;
            file = event.target.files[0];
            var reader = new FileReader();
            //转base64
            reader.onload = function (e) {
                _this.editForm.imgUrl = e.target.result; //将图片路径赋值给src
                _this.uploadImageChoose = true;
                if (fileList.length > 1) {
                    _this.$refs.imageupload.uploadFiles.splice(0, 1);//上传列表保留最新更换内容，避免多次上传
                }
            };
            reader.readAsDataURL(file);
        },
        targetChange: function (value) {
            if (value === "_no")
                this.editForm.url = "#";
        },
        handleImageEnlarge(_url) { //放大图片
            if (_url) {
                this.enlargeImage = _url;
                this.isEnlargeImage = !this.isEnlargeImage;
            }
        },
        handleSort(index, row) { //显示排序设置框
            this.editForm = Object.assign({}, row);
            this.isSortDialogVisible = true;
            this.sortNum = row.sort;
            this.editTableIndex = index;
        },
        rowSortConfirm() {     //设置排序确定
            this.editForm.sort = this.sortNum;
            this.$set(this.tableData, this.editTableIndex, this.editForm);
            this.tableData.sort((a, b) => (a.sort > b.sort) ? 1 : (a.sort === b.sort) ? ((a.sort > b.sort) ? 1 : -1) : -1);
            this.sortNum = 0;
            this.editForm = {};
            this.isSortDialogVisible = false;
            this.editTableIndex = -1;
        }
    },
    template: `
    <div>
        <div style="position: fixed; top: 55px; left: 0; width: 90%; height: 55px; padding: 5px 5%; z-index: 10;">
            <el-button type="primary" @click="addRow">添加</el-button>
        </div>
        <div style="width: 100%; height: 35px;"></div>
        <el-table
            :data="tableData"
            border
            style="width: 100%; margin-top: 10px;">
            <el-table-column
                fixed
                prop="imgUrl"
                label="图片"
                width="150">
                <template v-slot:default="scope">
                    <div v-if="isImageLink" class="avatarimagebox">
                       <el-avatar shape="square" :size="80" :src="scope.row.imgUrl"></el-avatar> 
                        <div class="avatarimglayer" @click="handleImageEnlarge(scope.row.imgUrl)">
                            <i class="el-icon-view"></i>
                        </div>
                    </div>
                    <span v-else>文字链接</span>                
                </template>
            </el-table-column>
            <el-table-column
                prop="title"
                label= "显示名称"
                width="170">
            </el-table-column>
            <el-table-column
                prop="desc"
                label= "描述信息"
                width="260">
            </el-table-column>
            <el-table-column
                prop="url"
                label="链接地址">
            </el-table-column>
            <el-table-column
                prop="target"
                label="打开方式"
                :formatter="targetFormatter"
                width="100">
            </el-table-column>
            <el-table-column
                label="操作"
                width="160">
                <template v-slot:default="scope">
                    <el-button @click="handleEdit(scope.$index, scope.row)" type="text" size="small">编辑</el-button>
                    <el-button @click="handleSort(scope.$index, scope.row)" type="text" size="small">排序</el-button>
                    <el-button @click="handleDelete(scope.$index, scope.row)" type="text" size="small">移除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
	        <el-form :model="editForm" label-width="80px" ref="editForm" :rules="formRules">
		        <el-form-item label="图片链接" v-if="isImageLink" class="imageItem">
                    <el-upload
                        class="avatar-uploader"
                        ref="imageupload"
                        action="fakeurl"
                        accept="image/*"
                        :show-file-list="false"
                        :auto-upload="false"
                        :multiple="false"
                        :http-request="uploadImage"
                        :on-change="editPreview">
                        <img :src="editForm.imgUrl" class="avatar">
                    </el-upload>
                    <el-checkbox v-model="isCloudUpload" style="margin: 25px;">云存储</el-checkbox>
			    </el-form-item>
			    <el-form-item label="显示名称" prop="title">
				    <el-input v-model="editForm.title"></el-input>
			    </el-form-item>
                <el-form-item label="描述信息" prop="desc">
				    <el-input v-model="editForm.desc"></el-input>
			    </el-form-item>
                <el-form-item label="文本内容" prop="contents">
				    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}"
                              placeholder="请输入内容"
                              v-model="editForm.contents"></el-input>
			    </el-form-item>
			    <el-form-item label="链接地址" prop="url">
				    <el-input v-model="editForm.url" placeholder="http或https开头"></el-input>
			    </el-form-item>
			    <el-form-item label="打开方式" prop="target">
				    <el-select v-model="editForm.target" clearable placeholder="请选择" @change="targetChange">
                        <el-option
                            v-for="item in targetOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
			    </el-form-item>
		    </el-form>
		    <div slot="footer" class="dialog-footer">
			    <el-button @click.native="editFormVisible = false">取消</el-button>
			    <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
		    </div>
	    </el-dialog>
        <!-- 放大弹窗 -->
        <el-dialog title="预览" 
        	:visible.sync="isEnlargeImage" 
        	:modal-append-to-body="false" 
        	top="30px" 
        	width="50%">
            	<img @click="isEnlargeImage = false" style="width:100%;" :src="enlargeImage">
        </el-dialog>
        <!-- 编辑排序 -->
        <el-dialog title="设置排序" 
        	:visible.sync="isSortDialogVisible" 
        	:modal-append-to-body="false" 
        	top="30px" 
        	width="230px">
            	<el-input-number v-model="sortNum" :min="1" :max="50"></el-input-number>
            <div slot="footer" class="dialog-footer">
			    <el-button type="primary" @click.native="rowSortConfirm">确定</el-button>
		    </div>
        </el-dialog>
    </div>
  `
});